package com.skywolf.chem.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.skywolf.chem.usercenter.constant.RoleConstant;
import com.skywolf.chem.usercenter.entity.Role;
import com.skywolf.chem.usercenter.entity.UserRole;
import com.skywolf.chem.usercenter.mapper.UserRoleMapper;
import com.skywolf.chem.usercenter.pojo.param.UserRoleParam;
import com.skywolf.chem.usercenter.service.IUserRoleService;
import com.skywolf.chem.usercenter.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 系统用户和角色关系表 服务实现类
 * </p>
 *
 * @author
 * @since 2019-12-03
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

    @Autowired
    private IUserService userService;

    @Autowired
    private UserRoleMapper userRoleMapper;


    @Override
    public void saveUserRole(UserRoleParam userRoleParam) {
        Long userId = userRoleParam.getUserId();
        //校验用户存不存在
        userService.checkExistUser(userId);

        //删除现有的用户角色关系
        UpdateWrapper<UserRole> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId);
        this.remove(updateWrapper);

        //保存现在的用户角色
        List<UserRole> userRoleList = new ArrayList<>();
        userRoleParam.getRoleIdList().forEach(roleId -> userRoleList.add(new UserRole(userId, roleId)));
        this.saveBatch(userRoleList);
    }

    @Override
    public List<Role> listUserRole(Long userId) {
        //校验用户存不存在
        userService.checkExistUser(userId);
        return userRoleMapper.selectByUserId(userId);
    }

    @Override
    public boolean isSuperAdmin(Long userId) {
        List<Role> roleList = listUserRole(userId);
        if (roleList.isEmpty()) {
            return false;
        }
        return roleList.stream().anyMatch(e -> RoleConstant.SUPER_ADMIN.equals(e.getRoleName()));
    }
}
